
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class SocketClient {
    public static void main(String[] args) throws IOException {
        // 1. 创建Socket，指定服务器的IP地址和端口号
        Socket socket = new Socket("localhost", 8080);

        System.out.println("连接服务端成功...");

        // 2. 获取输入输出流
        BufferedReader inputFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter outputToServer = new PrintWriter(socket.getOutputStream(), true);

        Scanner scanner = new Scanner(System.in);

        // 3. 循环读取用户输入并发送到服务器
        while (true) {
            System.out.print("Enter a message to send to the server (type 'exit' to quit): ");
            String userInput = scanner.nextLine();
            if ("exit".equalsIgnoreCase(userInput)) {
                // 关闭Socket连接
                break;
            }
            outputToServer.println(userInput);
            //读取服务器的响应并打印
            String response = inputFromServer.readLine();
            System.out.println("Server responded: " + response);
        }

        // 4. 读取服务器的响应并打印
        //String response;
        //while ((response = inputFromServer.readLine()) != null) {
        //    System.out.println("Server responded: " + response);
        //}

        // 5. 关闭资源
        scanner.close();
        inputFromServer.close();
        outputToServer.close();
        socket.close();
    }
}
